const http = require('http')
const url = require('url')
// const fs = require('fs')
const routes = require('./module/routes')
const ejs = require('ejs')

http.createServer(function(req, res) {
  // 创建静态web服务
  routes.static(req, res, 'static')

  // 路由
  let pathname = url.parse(req.url).pathname

  // 获取请求类型
  console.log(req.method)
  if(pathname === '/news') {
    // 获取get传值
    var query = url.parse(req.url, true).query
    // var query = url.parse(req.url).query  res.end(query)
    res.writeHead(200, {'Content-Type': 'text/json;charset=urf-8'})
    res.end('get传值获取成功')
  } else if(pathname === '/login') {
    // post演示

    ejs.renderFile('./views/form.ejs', {}, (err, data) =>{
      res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
      res.end(data)
    })

  } else if(pathname === '/doLogin') {
    // 获取post传值
    var postData = ''
    req.on('data', (chunk) => {
      postData += chunk
    })

    req.on('end', (err) => {
      console.log(postData)
      res.end(postData)
    })

  } else if(pathname === '/list') {
    let msg = '数据库里面获取的数据';
    let list = [
      {
        title: '新闻1'
      },
      {
        title: '新闻2'
      },
      {
        title: '新闻3'
      },
      {
        title: '新闻4'
      }
    ]
    ejs.renderFile('./views/list.ejs', {msg: msg, list: list}, (err, data) => {
      res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
      res.end(data)
    })
    
  } else if (pathname === '/register') {
    res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
    res.end('register')
  } else if (pathname === '/admin') {
    res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
    res.end('admin')
  // } else {
  //   let data = fs.readFileSync('./static/404.html')
  //   if(data) {
  //     res.writeHead(404, {'Content-Type':'text/html;charset=utf-8'})
  //     res.end(data)
  //   }
  }

}).listen(8081)
